package com.dbky.alg.core.validate.code;

import com.dbky.alg.core.properties.AlgSecurityProperties;
import com.dbky.alg.core.properties.SecurityConstants;
import com.dbky.alg.core.validate.code.sms.SmsCodeSender;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.temporal.ChronoUnit;
import java.util.Random;

/**
 * @Auther: tianchao
 * @Date: 2021/12/12 11:53
 * @Description:
 */
@RestController
public class ValidateCodeController {

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
    @Autowired
    private AlgSecurityProperties securityProperties;

    @Autowired
    private ValidateCodeGenerator imageValidateCodeGenerator;

    @Autowired
    private ValidateCodeGenerator smsValidateCodeGenerator;

    @Autowired
    private ValidateCodeProcessorHolder validateCodeProcessorHolder;

    @Autowired
    private SmsCodeSender smsCodeSender;

    @GetMapping(
            SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX+"/{type}"
    )
    public void createCode(
            HttpServletRequest request,
            HttpServletResponse response,
            @PathVariable(value = "type") String type
        ) throws Exception {
        validateCodeProcessorHolder.findValidateCodeProcessor(type)
                .create(new ServletWebRequest(request, response));
    }

    @GetMapping("/code/sms")
    public void createSmsCode(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletRequestBindingException {
        String mobile = ServletRequestUtils.getRequiredStringParameter(request, "mobile");
        ValidateCode smsCode = smsValidateCodeGenerator.generate(new ServletWebRequest(request));
        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, smsCode);
        smsCodeSender.send(mobile, smsCode.getCode());
    }
}
